package com.oj.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.oj.entity.Mail;
import com.oj.entity.Message;
import com.oj.entity.User;
import com.oj.mapper.MailMapper;
import com.oj.mapper.MessageMapper;
import com.oj.service.UserService;
import com.oj.util.CodeMsg;
import com.oj.util.DateUtil;
import com.oj.util.Html2Text;
import com.oj.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Controller
@RequestMapping
public class MailController {
    @Autowired
    private UserService userService;

    @Autowired
    private MailMapper mailMapper;

    @RequestMapping(value = {"/mails/new"}, method = RequestMethod.GET)
    public String mailNew(Model model){
        return "mail/mail-edit";
    }

    @RequestMapping(value = {"/mails",
            "/mails/page/{pageNum}"}, method = RequestMethod.GET)
    public ModelAndView mailsRecv(@PathVariable(value = "pageNum",required = false)Integer pageNum,
                                  @RequestParam(value = "pageSize",required = false, defaultValue = "50")Integer pageSize,
                                  HttpServletRequest request){
        if (pageNum == null) {
            pageNum = 1;
        }
        User user = userService.getUserBySession(request);
        if (user == null) {
            return null;
        }
        PageHelper.startPage(pageNum,pageSize);
        Page<Mail> mails = mailMapper.getMailsRecv(user.getUsername());
        for (Mail mail: mails) {
            if (mail.getTitle().length() > 20) {
                mail.setTitle(mail.getTitle().subSequence(0, 20)+"...");
            }
            String bufString = new String();
            bufString = Html2Text.RemoveHtml(((mail.getContent().length()>200)?(mail.getContent()).substring(0, 200):mail.getContent()));
            mail.setContent(((bufString.length()>50)?(bufString).substring(0, 50)+"...":bufString));

            mail.setSendUser(userService.query(mail.getFrom_user()));
            mail.setRecvUser(userService.query(mail.getTo_user()));
            mail.setFriendlyDate(DateUtil.toFriendlyDate(mail.getCreate_date()));
        }
        PageInfo<Mail> pageInfo = new PageInfo<>(mails);
        ModelAndView mv = new ModelAndView();
        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("mail/mails-recv.html");
        return mv;
    }
    @RequestMapping(value = {"/mails/send",
            "/mails/send/page/{pageNum}"}, method = RequestMethod.GET)
    public ModelAndView mailsSend(@PathVariable(value = "pageNum",required = false)Integer pageNum,
                                  @RequestParam(value = "pageSize",required = false, defaultValue = "50")Integer pageSize,
                                  HttpServletRequest request){
        if (pageNum == null) {
            pageNum = 1;
        }
        User user = userService.getUserBySession(request);
        if (user == null) {
            return null;
        }
        PageHelper.startPage(pageNum,pageSize);
        Page<Mail> mails = mailMapper.getMailsSend(user.getUsername());
        for (Mail mail: mails) {
            if (mail.getTitle().length() > 20) {
                mail.setTitle(mail.getTitle().subSequence(0, 20)+"...");
            }
            String bufString = new String();
            bufString = Html2Text.RemoveHtml(((mail.getContent().length()>200)?(mail.getContent()).substring(0, 200):mail.getContent()));
            mail.setContent(((bufString.length()>50)?(bufString).substring(0, 50)+"...":bufString));

            mail.setSendUser(userService.query(mail.getFrom_user()));
            mail.setRecvUser(userService.query(mail.getTo_user()));
            mail.setFriendlyDate(DateUtil.toFriendlyDate(mail.getCreate_date()));
        }
        PageInfo<Mail> pageInfo = new PageInfo<>(mails);
        ModelAndView mv = new ModelAndView();
        mv.addObject("pageInfo", pageInfo);
        mv.setViewName("mail/mails-send.html");
        return mv;
    }

    @ResponseBody
    @GetMapping("/api/mail/query")
    public Result<Mail> topic(@RequestParam Map<String, Object> map, HttpServletRequest request){
        User user = userService.getUserBySession(request);
        if (user == null) {
            return Result.error(CodeMsg.USER_NOT_LOGIN.locale());
        }
        Integer id = null;
        if (map.get("id") != null && !"".equals(map.get("id").toString())) {
            id = Integer.parseInt(map.get("id").toString());
        }
        Mail mail = mailMapper.query(id);
        if (mail == null) {
            return Result.error(CodeMsg.INNER_FAULT.locale());
        }
        mail.setSendUser(userService.query(mail.getFrom_user()));
        mail.setRecvUser(userService.query(mail.getTo_user()));
        mail.setFriendlyDate(DateUtil.toFriendlyDate(mail.getCreate_date()));

        return Result.success(mail);
    }

    @ResponseBody
    @PostMapping(value = "/api/mail/postmail")
    public Result postMail(@RequestParam Map<String, Object> map, HttpServletRequest request){
        try {
            Mail mail = new Mail();
            User user = userService.getUserBySession(request);
            if (user == null) {
                return Result.error(CodeMsg.USER_NOT_LOGIN.locale());
            }
            mail.setFrom_user(user.getUsername());

            if (map.get("sendto").toString().length() == 0) {
                return Result.error(CodeMsg.INPUT_CONTENT_NULL.locale());
            }
            mail.setTo_user(map.get("sendto").toString());
            User toUser = userService.query(mail.getTo_user());
            if (toUser == null) {
                return Result.error(CodeMsg.INPUT_CONTENT_NULL.locale());
            }

            if (map.get("content").toString().length() == 0) {
                return Result.error(CodeMsg.INPUT_CONTENT_NULL.locale());
            }
            mail.setContent(map.get("content").toString());

            Date dt = new Date();
            SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            mail.setCreate_date(Timestamp.valueOf(simpleDate.format(dt)));

            if (map.get("title") != null) {
                mail.setTitle(map.get("title").toString());
            } else {
                mail.setTitle("");
            }
            if (mailMapper.insert(mail)) {
                return Result.success();
            }
        } catch (Exception e) {
            log.error("newMail Exception."+ e.getMessage());
        }
        return Result.error(CodeMsg.INNER_FAULT.locale());
    }
}
